// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const DB1 = cloud.database().collection('wait_pay');
  const DB2 = cloud.database().collection('rider_inf');
  const DB3 = cloud.database().collection('wait_right');
  const _ = cloud.database().command;
  if (event.type == 'getdata') {
    //查询订单和骑手信息
    let order_inf = await DB1.where({ pay_courier_inf: null }).get();
    let rider_inf = await DB2.where({ rider_id: event.rider_inf.rider_id }).get();
    let order_wait_inf = await DB3.get();
    return { order_inf, rider_inf ,order_wait_inf};
  } else if (event.type == 'update_rider') {
    //更新骑手接单信息 
    let rider_infs  = {'_id':event.rider_inf._id,'rider_name':event.rider_inf.rider_name,'rider_phone':event.rider_inf.rider_phone,'rider_id':event.rider_inf.rider_id,'rider_not_name':event.rider_inf.rider_not_name,'rider_not_phone':event.rider_inf.rider_not_phone}
    let order_inf = await DB1.doc(event.id).update({
      data: { pay_courier_inf: _.set(rider_infs), rider_id: event.rider_inf.rider_id }
    });
    let rider_inf = await DB2.doc(event.rider_inf._id).update({
      data: { ride_number: _.inc(1) }
    })
    return { order_inf, rider_inf };
  } else if (event.type == 'getorder_rider') {
    //
    let order_inf = await DB1.where({ pay_courier_inf: _.neq(null), rider_id: _.eq(event.rider_id) }).get();
    return order_inf;
  } else if (event.type == 'back_rider') {
    //撤销骑手接的单 
    let order_inf = await DB1.doc(event.id).update({
      data: { pay_courier_inf: null, rider_id: null }
    });
    let rider_inf = await DB2.doc(event.rider_inf._id).update({
      data: { ride_number: _.inc(-1) }
    })
    return { order_inf, rider_inf };
  } else if (event.type == 'mail_money') {
    return await DB1.doc(event.id).update({
      data: {
        pay_aftermoney: event.mail_money,
        pay_store_weight: event.mail_weight,
        pay_store_inf: event.mail_inf,
      }
    });
  } else if (event.type == 'mail_delect') {
    //删除等待订单
   const result =  DB1.doc(event.id).remove();
   return  result;
    
  }
}